<template>
  <div class="profile-container">
    <!-- 充值对话框 -->
    <el-dialog
      v-model="depositDialogVisible"
      title="账户充值"
      width="400px"
    >
      <el-form :model="depositForm" label-width="80px">
        <el-form-item label="充值金额">
          <el-input-number
            v-model="depositForm.amount"
            :min="1"
            :precision="2"
            :step="10"
            style="width: 100%;"
          ></el-input-number>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="depositDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleDeposit" :loading="depositLoading">
            确认充值
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 提现对话框 -->
    <el-dialog
      v-model="withdrawDialogVisible"
      title="账户提现"
      width="400px"
    >
      <el-form :model="withdrawForm" label-width="80px">
        <el-form-item label="提现金额">
          <el-input-number
            v-model="withdrawForm.amount"
            :min="1"
            :max="userBalance"
            :precision="2"
            :step="10"
            style="width: 100%;"
          ></el-input-number>
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="withdrawForm.description" placeholder="可选"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="withdrawDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleWithdraw" :loading="withdrawLoading">
            确认提现
          </el-button>
        </span>
      </template>
    </el-dialog>

    <el-card class="profile-card">
      <template #header>
        <div class="card-header">
          <span>个人信息</span>
          <el-button type="primary" size="small" @click="editMode = !editMode">
            {{ editMode ? '取消' : '编辑' }}
          </el-button>
        </div>
      </template>

      <el-form
        :model="profileForm"
        :rules="rules"
        ref="profileFormRef"
        label-width="100px"
        :disabled="!editMode"
      >
        <el-form-item label="用户名">
          <el-input v-model="profileForm.username" disabled style="max-width: 300px;"></el-input>
        </el-form-item>

        <el-form-item label="邮箱" prop="email">
          <el-input v-model="profileForm.email" style="max-width: 300px;"></el-input>
        </el-form-item>

        <el-form-item label="手机号码" prop="phone">
          <el-input v-model="profileForm.phone" style="max-width: 300px;"></el-input>
        </el-form-item>

        <el-form-item v-if="editMode">
          <el-button type="primary" @click="saveProfile" :loading="loading">保存</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card class="profile-card">
      <template #header>
        <div class="card-header">
          <span>账户余额</span>
        </div>
      </template>

      <div class="wallet-balance">
        <div class="balance-label">当前余额</div>
        <div class="balance-amount">¥{{ userBalance.toFixed(2) }}</div>
        <div class="wallet-actions">
          <el-button type="primary" @click="showDepositDialog">充值</el-button>
          <el-button type="warning" @click="showWithdrawDialog">提现</el-button>
        </div>
      </div>
    </el-card>

    <el-card class="profile-card">
      <template #header>
        <div class="card-header">
          <span>修改密码</span>
        </div>
      </template>

      <el-form
        :model="passwordForm"
        :rules="passwordRules"
        ref="passwordFormRef"
        label-width="100px"
      >
        <el-form-item label="当前密码" prop="currentPassword">
          <el-input v-model="passwordForm.currentPassword" type="password" show-password style="max-width: 300px;"></el-input>
        </el-form-item>

        <el-form-item label="新密码" prop="newPassword">
          <el-input v-model="passwordForm.newPassword" type="password" show-password style="max-width: 300px;"></el-input>
        </el-form-item>

        <el-form-item label="确认新密码" prop="confirmPassword">
          <el-input v-model="passwordForm.confirmPassword" type="password" show-password style="max-width: 300px;"></el-input>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="changePassword" :loading="passwordLoading">修改密码</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 观影数据统计 -->
    <MovieStatsCard />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElInputNumber, ElDialog, ElForm, ElFormItem, ElButton, ElCard, ElInput } from 'element-plus'
import { useUserStore } from '../store/user'
import { useWalletStore } from '../store/wallet'
import type { FormInstance, FormRules } from 'element-plus'
// import axios from 'axios' // <-- 注释掉默认导入
import axiosInstance from '../utils/axiosInstance' // <-- 导入配置好的实例
import MovieStatsCard from '../components/MovieStatsCard.vue'

const userStore = useUserStore()
const walletStore = useWalletStore()
const editMode = ref(false)
const loading = ref(false)
const passwordLoading = ref(false)
const profileFormRef = ref<FormInstance>()
const passwordFormRef = ref<FormInstance>()

// 钱包相关
const userBalance = ref(0)
const depositDialogVisible = ref(false)
const depositLoading = ref(false)
const depositForm = ref({
  amount: 100
})

// 新增提现相关状态
const withdrawDialogVisible = ref(false)
const withdrawLoading = ref(false)
const withdrawForm = ref({
  amount: 50,
  description: ''
})

// 个人信息表单
const profileForm = reactive({
  username: '',
  email: '',
  phone: '',
  address: ''
})

// 修改密码表单
const passwordForm = reactive({
  currentPassword: '',
  newPassword: '',
  confirmPassword: ''
})

// 表单验证规则
const rules = reactive<FormRules>({
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ],
  phone: [
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  address: [
    { required: true, message: '请输入收货地址', trigger: 'blur' }
  ]
})

// 密码表单验证规则
const passwordRules = reactive<FormRules>({
  currentPassword: [
    { required: true, message: '请输入当前密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能少于6个字符', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能少于6个字符', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认新密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== passwordForm.newPassword) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
})

// 初始化用户信息
onMounted(async () => {
  try {
    // 获取用户完整信息
    const response = await axiosInstance.get('/users/profile')
    if (response.data) {
      profileForm.username = response.data.username || ''
      profileForm.email = response.data.email || ''
      profileForm.phone = response.data.phone || ''
      profileForm.address = response.data.address || ''
      userBalance.value = response.data.balance || 0
    }
  } catch (err) {
    console.error("获取用户信息失败:", err)
    // 如果API请求失败，尝试从store获取基本信息
    if (userStore.user) {
      profileForm.username = userStore.user.username
      profileForm.email = userStore.user.email || ''
    }
  }
})

// 保存个人信息
const saveProfile = async () => {
  if (!profileFormRef.value) return

  await profileFormRef.value.validate(async (valid) => {
    if (valid) {
      loading.value = true

      try {
        // 这里应该调用API保存用户信息
        // const response = await axiosInstance.put('/users/profile', profileForm); // <-- 将来也要用 axiosInstance
        // 模拟API调用 (需要移除)
        await new Promise(resolve => setTimeout(resolve, 1000))

        // 更新本地用户信息
        if (userStore.user) {
          userStore.user.email = profileForm.email
          // 更新其他信息...

          // 保存到localStorage
          localStorage.setItem('user', JSON.stringify(userStore.user))
        }

        ElMessage.success('个人信息已更新')
        editMode.value = false
      } catch (error) {
        ElMessage.error('保存失败，请稍后再试')
      } finally {
        loading.value = false
      }
    }
  })
}

// 修改密码
const changePassword = async () => {
  if (!passwordFormRef.value) return

  await passwordFormRef.value.validate(async (valid) => {
    if (valid) {
      passwordLoading.value = true

      try {
        // 调用后端API修改密码 - 使用新的路径，不再需要用户ID
        const response = await axiosInstance.post( // <-- 使用 axiosInstance
          // 注意：基础 URL 已在 axiosInstance 中配置，这里用相对路径即可
          `/users/profile/change-password`,
          {
            currentPassword: passwordForm.currentPassword,
            newPassword: passwordForm.newPassword
          }
        )

        // 检查后端是否返回了成功信息 (可以根据实际返回情况调整)
        // 例如，如果后端在成功时返回 { message: '...' }
        if (response.data && response.data.message === 'Password changed successfully') {
            ElMessage.success('密码已修改，请重新登录')

            // 清空表单
            passwordForm.currentPassword = ''
            passwordForm.newPassword = ''
            passwordForm.confirmPassword = ''

            // 登出用户
            setTimeout(() => {
              userStore.logout()
              window.location.href = '/login'
            }, 1500)
        } else {
             // 处理后端返回的其他消息或默认错误
             ElMessage.error(response.data?.message || '密码修改失败，请稍后重试')
        }

      } catch (error: any) {
         // 优先显示后端返回的错误消息
         const backendMessage = error.response?.data?.message;
         ElMessage.error(backendMessage || '密码修改失败，请确认当前密码是否正确');
         console.error("Change password error:", error.response || error);
      } finally {
        passwordLoading.value = false
      }
    }
  })
}

// 显示充值对话框
const showDepositDialog = () => {
  depositDialogVisible.value = true
}

// 处理充值
const handleDeposit = async () => {
  if (depositForm.value.amount <= 0) {
    ElMessage.warning('充值金额必须大于0')
    return
  }

  depositLoading.value = true
  try {
    console.log('前端 - 发送充值请求，金额:', depositForm.value.amount)
    const response = await axiosInstance.post('/users/balance/recharge', {
      amount: depositForm.value.amount
    })
    console.log('前端 - 充值响应:', response.data)

    if (response.data && response.data.user) {
      console.log('前端 - 充值成功，用户信息:', response.data.user)
      // 更新余额显示
      userBalance.value = response.data.user.balance || 0
      console.log('前端 - 更新余额显示:', userBalance.value)

      // 更新用户信息
      if (userStore.user) {
        userStore.user.balance = response.data.user.balance
        console.log('前端 - 更新store中的余额:', userStore.user.balance)
      }
    } else {
      console.log('前端 - 响应中没有用户信息')
    }

    ElMessage.success('充值成功')
    depositDialogVisible.value = false
  } catch (error: any) {
    const errorMsg = error.response?.data?.message || '充值失败，请稍后再试'
    ElMessage.error(errorMsg)
    console.error('前端 - 充值错误:', error)
    console.error('前端 - 错误详情:', error.response?.data)
    console.error('前端 - 错误状态:', error.response?.status)
  } finally {
    depositLoading.value = false
  }
}

// 显示提现对话框
const showWithdrawDialog = () => {
  // 确保提现金额不超过当前余额
  withdrawForm.value.amount = Math.min(50, userBalance.value > 0 ? userBalance.value : 50);
  withdrawDialogVisible.value = true
}

// 处理提现
const handleWithdraw = async () => {
  if (withdrawForm.value.amount <= 0) {
    ElMessage.warning('提现金额必须大于0')
    return
  }

  if (withdrawForm.value.amount > userBalance.value) { // Use userBalance directly
    ElMessage.warning('提现金额不能超过余额')
    return
  }

  withdrawLoading.value = true
  try {
    // 调用后端提现接口
    const response = await axiosInstance.post('/users/balance/withdraw', {
        amount: withdrawForm.value.amount,
        // description: withdrawForm.value.description // 备注可选，看后端是否需要
    });

    // 更新余额
    if (response.data && response.data.user) {
        userBalance.value = response.data.user.balance || 0;
        if (userStore.user) {
            userStore.user.balance = response.data.user.balance;
        }
    } else {
        // 如果后端没返回最新用户信息，手动更新或重新获取
        await userStore.fetchUserInfo(); // Or fetch profile again
        userBalance.value = userStore.user?.balance || 0;
    }

    ElMessage.success('提现成功')
    withdrawDialogVisible.value = false
  } catch (error: any) {
    ElMessage.error(error.response?.data?.message || '提现失败，请稍后再试')
    console.error('提现错误:', error.response || error);
  } finally {
    withdrawLoading.value = false
  }
}
</script>

<style scoped>
.profile-container {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
}


.profile-card {
  margin-bottom: 30px;
  background-color: rgba(255, 255, 255, 0.85); /* Semi-transparent white */
  border-radius: 8px; /* Ensure border-radius */
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.wallet-balance {
  text-align: center;
  padding: 20px 0;
}

.balance-label {
  font-size: 16px;
  color: #666;
  margin-bottom: 10px;
}

.balance-amount {
  font-size: 36px;
  font-weight: bold;
  color: #409EFF;
  margin-bottom: 20px;
}

.wallet-actions {
  display: flex;
  justify-content: center;
  gap: 20px;
}
</style>
